package com.ruoyi.pickup.service.impl;

import java.util.List;
import java.util.Date;
import java.math.BigDecimal;

import com.ruoyi.pickup.mapper.PickupPointApplicationsMapper;
import com.ruoyi.pickup.domain.PickupPointApplications;
import com.ruoyi.pickup.service.IPickupPointApplicationsService;
import com.ruoyi.leader.api.RemoteLeaderService;
import com.ruoyi.leader.api.domain.TGroupLeader;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 团长注册申请表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-15
 */
@Service
public class PickupPointApplicationsServiceImpl implements IPickupPointApplicationsService
{
    private static final Logger log = LoggerFactory.getLogger(PickupPointApplicationsServiceImpl.class);
    
    @Autowired
    private PickupPointApplicationsMapper pickupPointApplicationsMapper;

    @Autowired
    private RemoteLeaderService remoteLeaderService;

    /**
     * 查询团长注册申请表
     * 
     * @param applicationId 团长注册申请表主键
     * @return 团长注册申请表
     */
    @Override
    public PickupPointApplications selectPickupPointApplicationsByApplicationId(String applicationId)
    {
        return pickupPointApplicationsMapper.selectPickupPointApplicationsByApplicationId(applicationId);
    }

    /**
     * 查询团长注册申请表列表
     * 
     * @param pickupPointApplications 团长注册申请表
     * @return 团长注册申请表
     */
    @Override
    public List<PickupPointApplications> selectPickupPointApplicationsList(PickupPointApplications pickupPointApplications)
    {
        return pickupPointApplicationsMapper.selectPickupPointApplicationsList(pickupPointApplications);
    }

    /**
     * 新增团长注册申请表
     * 
     * @param pickupPointApplications 团长注册申请表
     * @return 结果
     */
    @Override
    public int insertPickupPointApplications(PickupPointApplications pickupPointApplications)
    {
        // 生成申请ID
        if (pickupPointApplications.getApplicationId() == null || pickupPointApplications.getApplicationId().isEmpty()) {
            pickupPointApplications.setApplicationId("APP" + System.currentTimeMillis());
        }
        // 设置默认状态
        if (pickupPointApplications.getStatus() == null || pickupPointApplications.getStatus().isEmpty()) {
            pickupPointApplications.setStatus("pending");
        }
        // 设置申请时间
        if (pickupPointApplications.getApplicationTime() == null) {
            pickupPointApplications.setApplicationTime(new Date());
        }
        // 设置创建时间
        if (pickupPointApplications.getCreatedAt() == null) {
            pickupPointApplications.setCreatedAt(new Date());
        }
        // 设置更新时间
        if (pickupPointApplications.getUpdatedAt() == null) {
            pickupPointApplications.setUpdatedAt(new Date());
        }
        return pickupPointApplicationsMapper.insertPickupPointApplications(pickupPointApplications);
    }

    /**
     * 修改团长注册申请表
     * 
     * @param pickupPointApplications 团长注册申请表
     * @return 结果
     */
    @Override
    public int updatePickupPointApplications(PickupPointApplications pickupPointApplications)
    {
        return pickupPointApplicationsMapper.updatePickupPointApplications(pickupPointApplications);
    }

    /**
     * 批量删除团长注册申请表
     * 
     * @param applicationIds 需要删除的团长注册申请表主键
     * @return 结果
     */
    @Override
    public int deletePickupPointApplicationsByApplicationIds(String[] applicationIds)
    {
        return pickupPointApplicationsMapper.deletePickupPointApplicationsByApplicationIds(applicationIds);
    }

    /**
     * 删除团长注册申请表信息
     * 
     * @param applicationId 团长注册申请表主键
     * @return 结果
     */
    @Override
    public int deletePickupPointApplicationsByApplicationId(String applicationId)
    {
        return pickupPointApplicationsMapper.deletePickupPointApplicationsByApplicationId(applicationId);
    }

    /**
     * 审核团长注册申请
     * 
     * @param pickupPointApplications 团长注册申请表
     * @return 结果
     */
    @Override
    @Transactional
    public int auditPickupApplication(PickupPointApplications pickupPointApplications)
    {
        // 设置更新时间
        pickupPointApplications.setUpdatedAt(new Date());
        
        // 更新申请表状态
        int result = pickupPointApplicationsMapper.updatePickupPointApplications(pickupPointApplications);
        
        // 如果审核通过，创建团长数据
        if ("approved".equals(pickupPointApplications.getStatus())) {
            createGroupLeader(pickupPointApplications);
        }
        
        return result;
    }

    /**
     * 批量审核团长注册申请
     * 
     * @param pickupPointApplications 团长注册申请表
     * @return 结果
     */
    @Override
    @Transactional
    public int batchAuditPickupApplications(PickupPointApplications pickupPointApplications)
    {
        // 获取所有待审核的申请
        PickupPointApplications queryParam = new PickupPointApplications();
        queryParam.setStatus("pending");
        List<PickupPointApplications> pendingApplications = pickupPointApplicationsMapper.selectPickupPointApplicationsList(queryParam);
        
        int successCount = 0;
        for (PickupPointApplications application : pendingApplications) {
            // 设置审核信息
            application.setStatus(pickupPointApplications.getStatus());
            application.setReviewerId(pickupPointApplications.getReviewerId());
            application.setReviewTime(pickupPointApplications.getReviewTime());
            application.setReviewNotes(pickupPointApplications.getReviewNotes());
            application.setUpdatedAt(new Date());
            
            // 更新申请表状态
            int result = pickupPointApplicationsMapper.updatePickupPointApplications(application);
            if (result > 0) {
                successCount++;
                // 如果审核通过，创建团长数据
                if ("approved".equals(application.getStatus())) {
                    createGroupLeader(application);
                }
            }
        }
        
        return successCount;
    }

    /**
     * 创建团长数据
     * 
     * @param application 团长注册申请
     */
    private void createGroupLeader(PickupPointApplications application)
    {
        try {
            log.info("开始创建团长数据，申请ID: {}", application.getApplicationId());
            log.info("申请人: {}, 自提点: {}", application.getApplicantName(), application.getPickupPointName());
            
            // 构建团长数据
            TGroupLeader leader = new TGroupLeader();
            leader.setLeaderId(application.getApplicationId());
            leader.setName(application.getApplicantName());
            leader.setPhone(application.getApplicantPhone());
            leader.setPickupName(application.getPickupPointName());
            leader.setPickupAddress(application.getPickupPointAddress());
            leader.setPickupType(application.getPickupPointType());
            leader.setAuditTime(application.getReviewTime());
            leader.setOrderAmount(BigDecimal.ZERO);
            leader.setOrderCount(0L);
            leader.setOrderItemCount(0L);
            leader.setStatus(1L); // 1表示有效
            
            // 调用远程服务创建团长数据
            R<Boolean> result = remoteLeaderService.addLeader(leader, SecurityConstants.INNER);
            
            if (result.getCode() == R.SUCCESS && Boolean.TRUE.equals(result.getData())) {
                log.info("团长数据创建成功，申请ID: {}", application.getApplicationId());
            } else {
                log.error("团长数据创建失败，申请ID: {}, 错误: {}", application.getApplicationId(), result.getMsg());
            }
            
        } catch (Exception e) {
            log.error("创建团长数据时发生异常，申请ID: {}, 错误: {}", application.getApplicationId(), e.getMessage(), e);
        }
    }
}
